import 'dart:async';

import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xiaozhou_ams_flutter/userprofile/ProfileEditPage.dart';
import 'package:xiaozhou_ams_flutter/userprofile/createFaceInterfacePage.dart';

class UserProfilePage extends StatefulWidget {
  const UserProfilePage({Key? key}) : super(key: key);

  @override
  _UserProfilePageState createState() => _UserProfilePageState();
}



class _UserProfilePageState extends State<UserProfilePage> {

  String _username = '';
  String _userId = '';
  String _avatarURL = 'http://image.aiyuye.shop/AvatarURL/ic_launcher.png';

  @override
  void initState() {
    super.initState();
    _loadUserInfo();
    _initCameras();  // 预先初始化摄像头
  }

  // 从 SharedPreferences 读取用户信息
  Future<void> _loadUserInfo() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _username = prefs.getString('username') ?? '默认用户名';
      _userId = prefs.getString('userId') ?? '默认用户ID';
      _avatarURL = prefs.getString('avatarURL') ?? 'http://image.aiyuye.shop/AvatarURL/ic_launcher.png';
    });
  }

  // 退出登录
  Future<void> _logout() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.clear(); // 清除所有SharedPreferences数据

    // 使用路由名称将用户重定向到登录页面
    if (mounted) {
      Navigator.of(context).pushReplacementNamed('/login');
    }

  }
  Future<void> _message() async {
    // 使用路由名称将用户重定向到消息页面
    if (mounted) {
      Navigator.of(context).pushReplacementNamed('/userprofile/MessagePage');
    }

  }
  Future<void> _create() async {
    // 使用路由名称将用户重定向到消息页面
    if (mounted) {
      Navigator.of(context).pushReplacementNamed('/userprofile/createFaceInterfacePage');
    }

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('用户信息'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            const SizedBox(height: 20),
            CircleAvatar(
              radius: 50,
              backgroundImage: NetworkImage(_avatarURL),
            ),
            const SizedBox(height: 10),
             Text('用户名：$_username', style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
             Text('ID: $_userId', style: const TextStyle(fontSize: 16)),
            Expanded(
              child: ListView(
                children: ListTile.divideTiles(
                  context: context,
                  tiles: [
                    ListTile(
                      leading: const Icon(Icons.message),
                      title: const Text('我的消息'),
                      onTap: () {/* 处理点击事件 */
                            _message();
                        },
                    ),
                    ListTile(
                      leading: const Icon(Icons.person),
                      title: const Text('个人资料'),
                      onTap: () {/* 处理点击事件 */
                        _navigateToProfilePage();
                      },
                    ),
                    ListTile(
                      leading: const Icon(Icons.account_box_outlined),
                      title: const Text('人脸录入'),
                      onTap: () {/* 处理点击事件 */
                        _handleTap();
                        },
                    ),
                    ListTile(
                      leading: const Icon(Icons.feedback),
                      title: const Text('意见反馈'),
                      onTap: () {/* 处理点击事件 */},
                    ),
                    ListTile(
                      leading: const Icon(Icons.info_outline),
                      title: const Text('关于我们'),
                      onTap: () {/* 处理点击事件 */},
                    ),
                    ListTile(
                      leading: const Icon(Icons.logout),
                      title: const Text('退出登录'),
                      onTap: () {
                        // 在这里处理用户退出登录的逻辑
                        // 比如清除用户状态、返回登录页等
                        _logout();
                        if (kDebugMode) {
                          print('用户选择了退出登录');
                        }
                        // Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => LoginPage()));
                      },
                    ),
                  ],
                ).toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }
  late String formattedTime;
  List<CameraDescription> _cameras = [];

  _navigateToProfilePage(){
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (context) => const ProfileEditPage(),
      ),
    );
  }
  Future<void> _initCameras() async {
    _cameras = await availableCameras();
  }


  void _navigateToFaceCapture() async {
    // 确保摄像头初始化完成
    if (_cameras.isEmpty) {
      await _initCameras();
    }
    if (_cameras.isNotEmpty) {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => createFaceInterfacePage(cameras: _cameras),
        ),
      );
    } else {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('错误'),
          content: Text('未检测到可用摄像头。'),
          actions: <Widget>[
            TextButton(
              child: Text('确定'),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        ),
      );
    }
  }

  void _handleTap() async {
    var status = await Permission.camera.status;

    if (status.isGranted) {
      _navigateToFaceCapture();
    } else {
      var result = await Permission.camera.request();
      if (result.isGranted) {
        _navigateToFaceCapture();
      } else {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('相机权限'),
            content: const Text('需要相机权限来进行人脸签到'),
            actions: <Widget>[
              TextButton(
                child: const Text('确定'),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        );
      }
    }
  }
}



